#!/bin/bash

#prepare the necessory for specified env and script

workdir=$1
scripts=$2
env=$3
components=$4

rm -fr ${workdir}
mkdir -p ${workdir}

#write the map script into such folder
scriptfile=${workdir}/map.sh
printf "%s" "${scripts}" > ${scriptfile}

# build the server list in such foler
serverfile=${workdir}/server.txt

hostfile="host-${env}.properties"
if [ -f "${hostfile}" ];
then
echo "INFO: use host file - ${hostfile}"
else
hostfile="../../host-${env}.properties"
echo "WARN: use host file - ${hostfile}"
fi

cp ${hostfile} "${workdir}"/host.txt
for comp in ${components} ;
do
grep "${comp}" ${hostfile}| cut -d= -f2 | tr -d ' '|tr -d '\r' >> ${serverfile}.tmp
done

#sort it as unique server
sort -u ${serverfile}.tmp > ${serverfile}
echo "INFO: build ${serverfile} : `cat $serverfile`"

keyfile="id_rsa-${env}-seek-keypair"
if [ -f "${keyfile}" ];then
echo "INFO:	use key file - ${keyfile}"
else
keyfile="../../resources/ec2/keys/id_rsa-${env}-seek-keypair"
echo "WARN:	use key file - ${keyfile}"
fi
cp ${keyfile} "${workdir}"/ssh_key